package com.chen.mysqltopostgres.util;

import com.chen.mysqltopostgres.constant.Constant;
import net.sf.jsqlparser.statement.create.table.Index;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.text.MessageFormat;

/**
 * @author: cgd
 * @description:
 * @date: 2022/8/22 16:08
 * @version: 1.0
 */
public class StatementUtils {
    /**
     * 索引预处理语句
     */
    public static final String PG_INDEX_STRING = "{0} IF NOT EXISTS {1} ON public.{2}  USING btree {3};";

    /**
     * 格式化SQL语句
     */
    public static String formatSql(String statement) {
        statement = statement.replaceFirst("\\(", "(" + Constant.SEPARATOR);
        statement = statement.replace(",", "," + Constant.SEPARATOR);

        StringBuilder stringBuilder = new StringBuilder(statement);
        int indexOf = stringBuilder.lastIndexOf(")");
        return stringBuilder.replace(indexOf, indexOf + 1, Constant.SEPARATOR + ")").toString();
    }

    /**
     * pgsql 索引填充
     */
    public static String pgsqlIndexFill(Index index, String tableName) {
        return MessageFormat.format(PG_INDEX_STRING, index.getType(), index.getName(), tableName
                , PlainSelect.getStringList(index.getColumns(), true, true));
    }
}
